<template :page.sync="page">
  <div class="el-card is-always-shadow el-card__body">

<avue-crud
  ref="crud"
  :option="option"
  :table-loading="listLoading"
  :data="reportApplyTableData"
  :page.sync="page"
  :search.sync="searchForm"
  @search-change="handleFilter"
  @selection-change="selectionChange"
  @refresh-change="refreshChange"
  @on-load="refreshChange">
  <template slot="searchMenu" slot-scope="{row,size}">
    <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);search()}" icon="el-icon-delete">清空</el-button>
  </template>
  <template slot-scope="scope" slot="lineCodeSearch">
    <el-select v-model="searchForm.lineCode" placeholder="线路" @change="changeLine" clearable>
      <el-option
        v-for="(item,index) in lineCodes"
        :key="index"
        :label="item.name"
        :value="item.code">
      </el-option>
    </el-select>
  </template>
  <template slot="stationCodeSearch" slot-scope="scope">
    <el-select v-model="searchForm.stationCode" placeholder="站点" clearable>
      <el-option
        v-for="(item,index) in stationCodes"
        :key="index"
        :label="item.name"
        :value="item.code">
      </el-option>
    </el-select>
  </template>
  <template slot="search" slot-scope="{row,size}" >
    <!-- <el-form-item label="差异金额范围" labelWidth="150px" style="width:450px">
      <el-input-number v-model="searchForm.errorAmountMin" :min="0" :max="99999998" label="差异金额范围" clearable></el-input-number>~
      <el-input-number v-model="searchForm.errorAmountMax" :min="1" :max="99999999" label="差异金额范围" clearable></el-input-number>
    </el-form-item> -->
    <el-form-item label="申请时间">
      <el-date-picker
        clearable
        v-model="searchForm.applyTime"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择日期">
      </el-date-picker>
    </el-form-item>
<!--    <el-form-item label="报表时间">-->
<!--      <el-date-picker-->
<!--        clearable-->
<!--        v-model="searchForm.reprotTime"-->
<!--        type="date"-->
<!--        value-format="yyyy-MM-dd"-->
<!--        placeholder="选择日期">-->
<!--      </el-date-picker>-->
<!--    </el-form-item>-->
    <el-form-item label="修改状态">
          <el-select
            :size="size"
            v-model="searchForm.isModify"
            type="select"
            placeholder="修改状态"
	    clearable>
            <el-option value="1" label="已完成"></el-option>
            <el-option value="0" label="待修改"></el-option>
          </el-select>
        </el-form-item>
  </template>


<template slot="menuRight">
    <el-button type="primary" size="mini" @click="examinationApproval()">审批</el-button>
    <el-button type="primary" size="mini" v-if="permissionList.deleteReport" @click="deleteReport()">高级删除</el-button>
<!--    <el-button type="primary" size="mini" @click="addModifyLimitTime()">设定期限</el-button>-->
    <el-button type="primary" size="mini"  @click="documentation()">导出</el-button>
  </template>
  <template slot-scope="scope" slot="menu">
    <el-button type="text" size="small" plain @click.stop="previewEditor(scope.row,1,'预览')">预览</el-button>
    <el-button type="text" size="small" v-if="scope.row.checkStatus == '4' && permissionList.deleteReport" plain @click.stop="repealAudit(scope.row)">撤回审批</el-button>
  </template>
</avue-crud>
<!--<add-modify-limit-time-vue v-if="addModifyLimitTimeVisible" ref="addModifyLimitTimeVue"></add-modify-limit-time-vue>-->
<report-mistake-info-editor ref="reportMistakeInfoEditor" v-if="isShowReportMistakeInfoEditor"></report-mistake-info-editor>
</div>

</template>

<script>
  import AddModifyLimitTimeVue from './addModifyLimitTimeVue';
  import reportMistakeInfoEditor from './reportMistakeInfo/Editor';
  import {
    getReportErrorList,
    updateReportApplyStatus,
    tableOption,
    removeById,
    repealAudit,
    updateReportCheckStatus
  } from "../../../api/subwayRat/reportMondify/reportApplyInfo";
  import {getLineLists,getStationLists} from "../../../api/subwayRat/reportMondify/reportMistakeInfo";
  import ElButton from '../../../../node_modules/element-ui/packages/button/src/button';
  import {exportDataToExcel} from "../../../api/subwayRat/exportSelf";
  import {getStationByCode,getLineAndStationByCode,setSearchFiledsEmpty} from "../../../api/subwayRat/commonCheck";
  import {mapGetters} from "vuex";
  export default {
    name: 'reportApplyInfo',
    components:{
      ElButton,
      AddModifyLimitTimeVue,reportMistakeInfoEditor
    },
    data() {
      return {
        listLoading: true,
        searchForm:{
          reportType: 1,
          lineCode:'9',
          stationCode:'',
          checkStatus: '2'
        },
        lineCodes:[],
        stationCodes:[],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          current: 1,// 当前页数
          pageSize: 20, // 每页显示多少条,
          size: 20,// 每页显示多少条
          isAsc: false// 是否倒序
        },
        isShowReportMistakeInfoEditor:false,//是否加载编辑页面
        reportApplyTableData: [],
        reportApplyTableCheck:[],
        option:{},
        addModifyLimitTimeVisible : false,
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        }
      }
    },
    computed: {
      ...mapGetters(['permissions']),
      permissionList () {
        return {
          deleteReport: this.vaildData(
            this.permissions.sw_st_report_delete,
            false
          ),
        };
      },
    },
    created() {
      this.changeLine("9")
      this.option=tableOption;
    },
    mounted() {
      this.search();
      this.initLine();
    },
    methods: {
      setSearchFiledsEmpty,
      refreshChange() {
        this.search()
      },
      previewEditor(row,showType,title){
        this.isShowReportMistakeInfoEditor=true;
        this.$nextTick(()=>{
          // this.$refs.reportMistakeInfoEditor.showType=-1;
          // this.$refs.reportMistakeInfoEditor.dialogTitle=title;
          // this.$refs.reportMistakeInfoEditor.previewEditor(row);
          this.$refs.reportMistakeInfoEditor.previewEditor(row,1,"预览");
        });

      },
      //撤回审批
      repealAudit(row){
        if (row.checkStatus != '4') {
          this.$message.error("只能撤回审批驳回的数据！");
        }
        this.$confirm("确认撤回审批?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          repealAudit(row.id)
            .then((data) => {
              this.$message.success("撤回审批成功");
              this.search()
              done();
            })
            .catch(() => {
              loading();
            });
        });
      },
      deleteReport(){
        if (this.$refs.crud.tableSelect.length < 1) {
          this.$message.error("请选择数据！");
          return false;
        }
        let ids = [];
        for (const table of this.$refs.crud.tableSelect) {
          ids.push(table.id);
        }
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const deletePromises = ids.map(id => removeById(id));
          Promise.all(deletePromises)
            .then((data) => {
              this.$message.success("删除成功");
              this.search()
              done();
            })
            .catch(() => {
              loading();
            });
        });
      },
      changeLine(v){
        let p={};
        p.userCode=this.$store.getters.userInfo.userCode;
        p.lineCode=v;
        getStationLists(p).then((res)=>{
          this.stationCodes=res.data.data;
          this.searchForm.stationCode='';
        })
      },
    //   async examinationApproval(){
    //     if(this.reportApplyTableCheck.length == 0){
    //       this.$message({message: '请勾选数据后审批',type: 'warning'});
    //       return;
    //     }
    //     for(let i=0;i<this.reportApplyTableCheck.length;i++){
    //       if(this.reportApplyTableCheck[i].checkStatus!=2){
    //         this.$message({message: '请选择待审批数据',type: 'warning'});
    //         return;
    //       }
    //     }
    //     let messageLSList = [];
    //     for(let i=0;i<this.reportApplyTableData.length;i++){
    //       let data = await getLineAndStationByCode({"lineCode":this.reportApplyTableData[i].lineCode, "code":this.reportApplyTableData[i].stationCode});
    //       messageLSList.push({
    //         "content":"站点：" + data.data[0].name,
    //         "lineCode":this.reportApplyTableData[i].lineCode,
    //         "stationCode":this.reportApplyTableData[i].stationCode
    //       })
    //     }
    //     var ids=[];
    //     this.reportApplyTableCheck.forEach(function (key, val) {
    //       ids[val] = key.id
    //     })
    //     let p = {
    //       messageLSList:JSON.stringify(messageLSList),
    //       //title:this.$store.getters.tag.label,
	  // title:'报表差错申请审批',
    //       msgType:"审批",
    //       type:"reportApplyInfo_001",
    //       ids : JSON.stringify(ids)
    //     };
    //     const h = this.$createElement;
    //     this.$msgbox({
    //       title: '消息',
    //       message: h('p', null, [
    //         h('span', null, '请选择通过或不通过 '),
    //       ]),
    //       showCancelButton: true,
    //       confirmButtonText: '审批通过',
    //       cancelButtonText: '审批不通过',
    //       beforeClose: (action, instance, done) => {
    //         if (action == 'confirm') {
    //           p.checkStatus = "3";
    //         } else{
    //           p.checkStatus = "4";
    //         }
    //         updateReportApplyStatus(p).then((res)=>{
    //           if(res.data.code == "1"){
    //             this.$message({
    //               message: '审批完成',
    //               type: 'success'
    //             });
    //             this.search();
    //           }
    //         });
    //         done();
    //       }
    //     }).then(action => {
    //     });
    //   },

      //审批不通过填写意见--此方法是切换通过不通过时，意见框也切换-比较繁琐
  async examinationApproval(){
    if(this.reportApplyTableCheck.length == 0){
        this.$message({message: '请勾选数据后审批',type: 'warning'});
        return;
    }
   
    let messageLSList = [];
    for(let i=0;i<this.reportApplyTableData.length;i++){
        let data = await getLineAndStationByCode({"lineCode":this.reportApplyTableData[i].lineCode, "code":this.reportApplyTableData[i].stationCode});
        messageLSList.push({
            "content":"站点：" + data.data[0].name,
            "lineCode":this.reportApplyTableData[i].lineCode,
            "stationCode":this.reportApplyTableData[i].stationCode
        })
    }
    
    var ids = [];
    this.reportApplyTableCheck.forEach(function (key, val) {
        ids[val] = key.id
    });

    let p = {
        messageLSList: JSON.stringify(messageLSList),
        title: '报表差错申请审批',
        msgType: "审批",
        type: "reportApplyInfo_001",
        ids: JSON.stringify(ids)
    };

    // 使用 this.$prompt 替代 this.$confirm
    this.$prompt('请输入审批意见（选填）', '审批确认', {
        confirmButtonText: '审批通过',
        cancelButtonText: '审批不通过',
        distinguishCancelAndClose: true,
        inputType: 'textarea', // 使用文本域方便输入多行文本
        inputPlaceholder: '请输入您的审批意见...',
        inputValidator: (value) => {
            // 可以添加输入验证逻辑（如果需要）
            return true;
        }
    }).then(({ value }) => {
        // 审批通过
        p.checkStatus = "3";
        p.sendNotice = "1";
        p.reserved3 = value || '';  // 获取用户输入的意见
        updateReportApplyStatus(p).then((res) => {
            if(res.data.code == "1"){
                this.$message({
                    message: '审批通过',
                    type: 'success'
                });
                this.search();
            }
        })
    }).catch((action) => {
        if (action === 'cancel') {
            // 审批不通过，需要获取用户输入的拒绝原因
            this.$prompt('请填写不通过原因（必填）', '不通过原因', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                inputType: 'textarea',
                inputValidator: (value) => {
                    if (!value || value.trim() === '') {
                        return '不通过原因不能为空';
                    }
                    return true;
                }
            }).then(({ value }) => {
                p.checkStatus = "4";
                p.reserved3 = value;  // 获取拒绝原因
		p.sendNotice = "1";
                updateReportApplyStatus(p).then((res) => {
                    if(res.data.code == "1"){
                        this.$message({
                            message: '审批不通过',
                            type: 'success'
                        });
                        this.search();
                    }
                })
            }).catch(() => {
                this.$message.info('已取消操作');
            });
        }
    });
},
      search(){
        this.searchForm.pageType=2;
        this.listLoading=true;
        this.page.size = this.page.pageSize;
        this.page.current = this.page.currentPage;
        Object.assign(this.searchForm,this.page);
        this.searchForm.userCode=this.$store.getters.userInfo.userCode;
        this.searchForm.pageNo = null;
        this.searchForm.reportType = 1;
        //日期范围
        let dates1 = this.searchForm.dates1;
        if(dates1!=null && dates1!=''){
          this.searchForm.startdate = dates1[0].substr(0,10);
          this.searchForm.enddate = dates1[1].substr(0,10);
        }
        getReportErrorList(this.searchForm).then((res)=>{
          this.reportApplyTableData=res.data.data.records;
          this.page.total=res.data.data.total;
          // this.page = res.data.data;
          // this.page.records = null;
          this.listLoading=false;
        });
      },
      clear(){
        this.searchForm = {};
        this.searchForm.errorAmountMin = 0;
        this.searchForm.errorAmountMax = 1;
      },
      addModifyLimitTime(){
        if(this.reportApplyTableCheck.length == 0){
          this.$message({message: '请勾选数据后设定期限',type: 'warning'});
          return;
        }
        this.addModifyLimitTimeVisible = true;
        this.$nextTick(()=>{
          this.$refs.addModifyLimitTimeVue.checkData = this.reportApplyTableCheck;
        });
      },
      async documentation(){
        // if(this.reportApplyTableCheck == 0){
        //   this.$message({message: '请勾选数据后导出',type: 'warning'});
        //   return;
        // }
        this.searchForm.pageNo=1;
        this.searchForm.pageSize=1000000000;
        this.searchForm.size=1000000000;
        if(this.reportApplyTableCheck.length>0){
          let newData = JSON.parse(JSON.stringify(this.reportApplyTableCheck));
          exportDataToExcel(newData,this.option.column,'车站修改报表申请');
        }else {
          let res=await getReportErrorList(this.searchForm);
          let data = res.data.data.records;
          exportDataToExcel(data,this.option.column,'车站修改报表申请');
        }
        // const ExportJsonExcel = require("js-export-excel");
        // var option = {};
        // option.fileName = "车站修改报表申请";
        // option.datas = [
        //   {
        //     sheetData: this.reportApplyTableCheck,
        //     sheetName: "车站修改报表申请",
        //     sheetFilter: ["id", "lineCode", "stationCode", "applyTime", "reprotTime", "errorClassification", "applyReason", "reportNameId", "creatorId", "creatorName", "modifyTime"
        //       , "isModify", "modifyLimitTime", "checkStatus" ],
        //     sheetHeader: ["序号", "线路", "站点", "申请时间", "报表日期", "差错类别", "申请原因", "报表名称", "申请人", "申请人工号", "更改日期", "修改状态", "修改期限（天）", "审批状态"],
        //     columnWidths: [5, 5],
        //   }
        // ];
        // var toExcel = new ExportJsonExcel(option);
        // toExcel.saveExcel();
      },
      selectionChange(list){
        this.reportApplyTableCheck=list;
      },
      handleFilter(params, done) {
        Object.assign(this.searchForm,params);
        this.search()
        done()
      },
      initLine(){
        let p={};
        p.userCode=this.$store.getters.userInfo.userCode;
        getLineLists(p).then((res)=>{
          this.lineCodes=res.data.data;
        });
      }
    }
  }
</script>
<style lang="scss">

</style>
